<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Application\Utils;

/**
 * Description of GenericManager
 *
 * @author dliebel
 */
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;

use Zend\Paginator\Adapter\DbTableGateway;
use Zend\Paginator\Paginator;
 
class GenericManager extends TableGateway {

    public $mess;
    private $confirmation;
    private $nametable;

    public function __construct($nameTable, Adapter $adapter = null, $databaseSchema = null, ResultSet $selectResultPrototype = null) {
        $this->nametable= $nameTable;
        return parent::__construct($nameTable, $adapter, $databaseSchema, $selectResultPrototype);
    }

    /**
     * retorna con el mensaje correspondiente si existe una excepción
     * @return type string
     */
    public function getMess() {
        return $this->mess;
    }
    /**
     * retorna un select(SQL) de la tabla en el cual pertenecer el modelo
     * @return type
     */
    public function getObjects() {
        $datos = $this->select();
        return $datos->toArray();
    }

    public function getObjectByID($id) {

        $id = (int) $id;
        $rowset = $this->select(array('id' => $id));
        $row = $rowset->current();

        if (!$row) {
            throw new \Exception("No hay registros asociados al valor $id");
        }
        return $row;
    }

    public function saveOrUpdate($data = array(), $id = null) {

        try {
            if ($id != null) {
                $this->update($data, array('id' => $id));
                echo "entro por update";
            } else {
                 echo "entro por new ";
                $this->insert($data);
            }
        } catch (ErrorException $ex) {
            $this->mess = $ex;
            return false;
        }
        return true;
    }

    public function delete($id = null) {

        try {
             $this->delete(array('id' => $id));
        } catch (ErrorException $ex) {
            $this->mess = $ex;
            return false;
        }
        return true;
    }
    /**
     * realizar el paginado
     * @param type $paginated
     * @return \Application\Utils\Paginator
     */
     public function fetchAll($paginated=false)
     {
         if ($paginated) {
             $dbTableGatewayAdapter = new DbTableGateway($this);
             $paginator = new Paginator($dbTableGatewayAdapter);
             return $paginator;
         }
         $resultSet = $this->tableGateway->select();
         return $resultSet;
     }

}

?>
